package com.linchong.jvm.gc;

import lombok.extern.slf4j.Slf4j;

import java.lang.ref.Reference;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.SoftReference;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

/**
 * @author linchong
 * @version 1.0
 * @Date: 2020-11-18 20:33
 * @Description: ReferenceType$
 */

public class ReferenceType {

	/**
	 * 被回收后放入到队列中
	 *
	 * 软引用被垃圾回收过后才会进入队列，
	 *
	 */
	private static ReferenceQueue<User> rq = new ReferenceQueue<>();

	private static void printQueue(String str){
		Reference<? extends User> obj = rq.poll();
		if(obj!=null){
			System.out.println("the gc Object reference ="+str+"="+obj.get());
		}


	}

	private static void testSoftReference() throws InterruptedException {
		List<SoftReference<User>> list = new ArrayList<SoftReference<User>>();
		for (int i = 0; i < 10; i++) {
			SoftReference<User> sr = new SoftReference<>(new User("soft " + i),rq);

			System.out.println("now the soft user =="+sr.get());
			list.add(sr);
		}

		System.gc();

		Thread.sleep(1_000);

		printQueue("soft");
	}

	private static void testWeakReference() throws InterruptedException {
		List<WeakReference<User>> list = new ArrayList<WeakReference<User>>();
		for (int i = 0; i < 10; i++) {
			WeakReference<User> sr = new WeakReference<>(new User("weak " + i),rq);

			System.out.println("now the weak user =="+sr.get());
			list.add(sr);
		}

		System.gc();

		Thread.sleep(1_000);
		printQueue("weak");
	}

	public static void main(String[] args) throws InterruptedException {
		testSoftReference();

		testWeakReference();
	}
}
